# This Python file uses the following encoding: utf-8

import threading
import time
from MySignals import global_ms
from db import ObjLink
from catchObj.catchTime import CatchTime
import func as func
from catchObj.TR import TR
from catchObj.ThreadRun import *
from PySide2.QtCore import QTime
import config
import json
import tushare as ts
from tuShare import TuShare
import catchObj.Stocks 

class CtrlThread(TR,TuShare):

    def __init__(self):
        super(CtrlThread, self).__init__(CtrlThread)
        #暂停中
        self.ctrlOrder = "pause"
        #stocksGroups
        self.stocksGroups = []
        #所有的股票信息
        self.stocks = []
        #线程数量信息
        self.threadsNum = 0
        #当前线程信息
        self.threads = {}
        #pages信息
        self.pages = 0
        #默认抓取时间
        self.timeInfo = {}
        #临时任务标记
        self.temporaryTaskName = ""
        #今日是否开盘
        self.openDay = False
        #tushare相关函数
        self.TuShare = TuShare()
        #主url
        self.hurl = 'http://hq.sinajs.cn/list='

        self.init()

    def init(self):
        global_ms.setTest.connect(self.updateTestOk)

    #从tushare获取所有股票
    def updateAllStocks(self):
        self.notice_msg("更新所有股票名称代码开始")
        self.TuShare.updateAllStocks()
        self.notice_msg("更新所有股票名称代码结束")

    def updateAllDaily(self):
        self.notice_msg("更新所有日线数据开始")
        for st in Stocks.stocks:
            print(st[0])
            self.TuShare.updateAllDaily(st[0])
        self.notice_msg("更新所有日线数据结束")


    #测试运行接口,返回测试结果,今天是否开盘,可以保证只运行一次哦,
    def updateTestOk(self, str):
        if str and not self.openDay:
            self.openDay = True


    #设置参数
    def setConfig(self, threadsNum, timeInfo):
        self.configIsUpdate = True
        self.timeInfo = timeInfo
        self.threadsNum = threadsNum
        if len(Stocks.stocks)%self.threadsNum == 0:
            Stocks.pages = len(Stocks.stocks)//self.threadsNum
        else:
            Stocks.pages = len(Stocks.stocks)//self.threadsNum+1
        return Stocks.pages

    #线程运行接口
    def run(self):
        #创建线程
        endPoint = 0
        threadsNum = 0

        while self.running.isSet():
            #只有控制线程重新启动的时候才更新抓取配置,抓取线程也重启
            #线程重启,所有的线程处于最后有1次运行中,这里更新配置是安全的
            if not self.flag.isSet():
                threadsNum = self.threadsNum
                taskCatch = False
                #计算线程配置
                Stocks.stocksGroups=[]
                Stocks.getStocksGroup()

            global_ms.setCtrlStatus.emit(self.statusName)
            self.flag.wait()

            #新的一天开始
            if time.time()>endPoint:
                self.notice_msg("重新部署时间点")
                #重新计算各个时间点
                catchtime = CatchTime(self.timeInfo)
                endPoint = catchtime.timeStamp['tpEndPoint']

                #任务归零false是未运行过
                taskCatch = False
                taskDelCatch = False
                taskTest = False
                taskToMongo = False
                taskDelFs =False

                #首次启动,如果当前任务时间点已过,就不在运行了
                if time.time()>catchtime.timeStamp['tpDelCatch']:
                    taskDelCatch = True
                if time.time()>catchtime.timeStamp['tpTest']:
                    taskTest = True
                if time.time()>catchtime.timeStamp['tpToMongo']:
                    taskToMongo = True
                if time.time()>catchtime.timeStamp['tpDelFs']:
                    taskDelFs = True

                self.openDay = False

            #到达指定的时间点运行指定的多线程任务
            if not taskDelCatch and time.time()>catchtime.timeStamp['tpDelCatch']:
                self.notice_msg("定时任务:删除抓取数据")
                ThDelCatch.init(1)
                ThDelCatch.Tstart()
                taskDelCatch = True
            if not taskDelFs and time.time()>catchtime.timeStamp['tpDelFs']:
                self.notice_msg("定时任务:删除分时数据")
                ThDelFs.init(1)
                ThDelFs.Tstart()
                taskDelFs = True
            if not taskTest and time.time()>catchtime.timeStamp['tpTest']:
                self.notice_msg("定时任务:测试抓取数据")
                ThTest.init(1)
                ThTest.Tstart()
                taskTest = True
            if self.openDay and not taskToMongo and time.time()>catchtime.timeStamp['tpToMongo']:
                self.notice_msg("定时任务:保存数据到mongo,整理分时数据")
                ThToMongo.init(1)
                ThToMongo.Tstart()
                taskToMongo = True

            #抓取到点关闭
            if self.openDay and not catchtime.isIn() and taskCatch:
                ThCatch.stop()
                taskCatch = False

            #抓取线程随着控制线程一起启动,开始抓取,控制线程就启动了,
            #抓取到点启动
            if self.openDay and catchtime.isIn() and not taskCatch:
                self.notice_msg("抓取线程启动")
                if catchtime.sorx() == 1:
                    ThCatch.timeOver = catchtime.timeStamp['tpEnd1']
                elif catchtime.sorx() == 2:
                    ThCatch.timeOver = catchtime.timeStamp['tpEnd2']
                else:
                    ThCatch.timeOver = catchtime.timeStamp['tpEndPoint']
                    print("抓取时间不对")
                ThCatch.init(threadsNum)
                ThCatch.Tstart()
                taskCatch = True

            #开启临时任务
            self.run2()

            time.sleep(1)
            global_ms.setNowTime.emit(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

    #这里只写临时任务
    def run2(self):
        #控制线程临时任务
        if self.temporaryTaskName != "":
            if self.temporaryTaskName == "delCatch":
                self.notice_msg("临时任务:删除抓取数据")
                ThDelCatch.init(1)
                ThDelCatch.Tstart()
            elif self.temporaryTaskName == "delFs":
                self.notice_msg("临时任务:删除分时数据")
                ThDelFs.init(1)
                ThDelFs.Tstart()
            elif self.temporaryTaskName == "test":
                self.notice_msg("临时任务:测试抓取")
                ThTest.init(1)
                ThTest.Tstart()
            elif self.temporaryTaskName == "toMongo":
                self.notice_msg("临时任务:保存数据到mongo,整理分时数据")
                ThToMongo.init(1)
                ThToMongo.Tstart()
                self.notice_msg("临时任务:保存到mongo结束")
            elif self.temporaryTaskName == "updateAllDialy":
                self.notice_msg("临时任务:更新所有日线数据")
                self.updateAllDaily()
            else:
                print("无临时任务")
            self.temporaryTaskName = ""

    #消息通知接口
    def notice_msg(self,msg):
        global_ms.setCtrlMsg.emit(msg+"|时间:"+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

    def pause(self):
        print(ThCatch.threads)
        ThCatch.stop()
        TR.pause()
